package vn.ikame.android.truyenf17;

import java.io.IOException;

import vn.ikame.android.adapter.ListStoryAdapter;
import vn.ikame.android.handler.CHandler;
import vn.ikame.android.utils.CStore;
import vn.ikame.android.utils.CommonUtils;
import vn.ikame.android.utils.XMLParser;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.google.ads.AdRequest;
import com.google.ads.AdSize;
import com.google.ads.AdView;
import com.google.android.apps.analytics.GoogleAnalyticsTracker;

public class StoryList extends Activity {
	public static final int DIALOG_DOWNLOAD_PROGRESS = 0;

	ListView list;
	ListStoryAdapter arrayAdapter;
	private AdView adView;

	public static boolean isRefresh = true;
	public static boolean trackGA = true;

	public static GoogleAnalyticsTracker generalTracker;
	public static GoogleAnalyticsTracker detailsTracker;

	// download
	private AlertDialog.Builder alert;
	private ProgressDialog mProgressDialog;

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.storylist);
		CHandler.store = new CStore(this);

		if (trackGA) {
			generalTracker = GoogleAnalyticsTracker.getInstance();
			generalTracker.startNewSession("UA-33515341-2",
					getApplicationContext());
			generalTracker.trackTransactions();
			generalTracker.trackPageView("FromF17WithLove");
			generalTracker.dispatch();
			trackGA = false;

			detailsTracker = GoogleAnalyticsTracker.getInstance();
			detailsTracker.startNewSession("UA-33515341-4",
					getApplicationContext());
			detailsTracker.trackTransactions();
			detailsTracker.trackPageView("FromF17WithLove_LaunchApp");
			detailsTracker.dispatch();
		}

		LinearLayout lLinLayout = (LinearLayout) findViewById(R.id.layoutstorylist);

		RelativeLayout.LayoutParams adParams2 = new RelativeLayout.LayoutParams(
				RelativeLayout.LayoutParams.WRAP_CONTENT,
				RelativeLayout.LayoutParams.WRAP_CONTENT);
		adParams2.addRule(RelativeLayout.ALIGN_BOTTOM);
		adParams2.addRule(RelativeLayout.CENTER_IN_PARENT);

		adView = new AdView(this, AdSize.SMART_BANNER, "a1502465d6a93ed");
		adView.loadAd(new AdRequest());

		// adView.setad

		lLinLayout.addView(adView, adParams2);

		if (CommonUtils.isNetworkConnected(this)) {
			if (isRefresh) {
				initStory();
				isRefresh = false;
			} else {
				arrayAdapter = new ListStoryAdapter(StoryList.this,
						R.layout.listview_story, CHandler.storyList);

				list = (ListView) findViewById(R.id.list_story);
				list.setAdapter(arrayAdapter);

				list.setOnItemClickListener(new OnItemClickListener() {

					@Override
					public void onItemClick(AdapterView<?> parent, View view,
							int position, long id) {
						// TODO Auto-generated method stub
						CHandler.storyName = CHandler.storyList.get(
								CHandler.storyList.size() - 1 - position)
								.getName();
						CHandler.storyID = CHandler.storyList.get(
								CHandler.storyList.size() - 1 - position)
								.getId();

						try {
							detailsTracker.trackPageView("ReadStory_"
									+ CHandler.storyName);
							detailsTracker.dispatch();
						} catch (Exception e) {
							// TODO: handle exception
						}

						startActivity(new Intent(StoryList.this, ChapList.class));
						StoryList.this.finish();
					}

				});

			}
		} else {
			alert = new AlertDialog.Builder(this);
			alert.setMessage("Vui lòng kiểm tra lại kết nối mạng");
			alert.setPositiveButton("Thử lại",
					new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog,
								int whichButton) {
							initStory();
						}
					});
			alert.setNegativeButton("Thoát",
					new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog,
								int whichButton) {
							StoryList.this.finish();
							System.gc();
							android.os.Process.killProcess(android.os.Process
									.myPid());
						}
					});

			alert.setCancelable(true);
			alert.show();

			arrayAdapter = new ListStoryAdapter(StoryList.this,
					R.layout.listview_story, CHandler.storyList);

			list = (ListView) findViewById(R.id.list_story);
			list.setAdapter(arrayAdapter);

			list.setOnItemClickListener(new OnItemClickListener() {

				@Override
				public void onItemClick(AdapterView<?> parent, View view,
						int position, long id) {
					// TODO Auto-generated method stub
					CHandler.storyName = CHandler.storyList.get(
							CHandler.storyList.size() - 1 - position).getName();
					CHandler.storyID = CHandler.storyList.get(
							CHandler.storyList.size() - 1 - position).getId();

					try {
						detailsTracker.trackPageView("ReadStory_"
								+ CHandler.storyName);
						detailsTracker.dispatch();
					} catch (Exception e) {
						// TODO: handle exception
					}

					startActivity(new Intent(StoryList.this, ChapList.class));
					StoryList.this.finish();
				}

			});
		}

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.layout.menu, menu);
		return true;
	}

	public void createAboutMessage() {
		alert = new AlertDialog.Builder(this);
		alert.setMessage(R.string.about);
		alert.setPositiveButton("Gửi mail",
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int whichButton) {
						final Intent emailIntent = new Intent(
								android.content.Intent.ACTION_SEND);

						/* Fill it with Data */
						emailIntent.setType("plain/text");
						emailIntent.putExtra(
								android.content.Intent.EXTRA_EMAIL,
								new String[] { "support@ikame.vn" });
						emailIntent.putExtra(
								android.content.Intent.EXTRA_SUBJECT,
								"Ứng dụng truyện ngắn - f145");
						emailIntent.putExtra(android.content.Intent.EXTRA_TEXT,
								"Nội dung: ");

						/* Send it off to the Activity-Chooser */
						startActivity(Intent.createChooser(emailIntent,
								"Send mail..."));
					}
				});

		alert.setNegativeButton("Đóng", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int whichButton) {
			}
		});
		alert.setCancelable(false);
		alert.show();
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.gotomark:
			if(CHandler.store.getStoryID() > 0){
				CHandler.isReadMarkChap = true;
				initChapList();
			} else {
				Toast.makeText(this, "Chưa có chap nào được đánh dấu", Toast.LENGTH_SHORT).show();
			}
			break;
		case R.id.refresh:
			if (CommonUtils.isNetworkConnected(this)) {
				initStory();
			} else {
				alert = new AlertDialog.Builder(this);
				alert.setMessage("Vui lòng kiểm tra lại kết nối mạng");
				alert.setPositiveButton("Thử lại",
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog,
									int whichButton) {
								initStory();
							}
						});
				alert.setNegativeButton("Thoát",
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog,
									int whichButton) {
								StoryList.this.finish();
								System.gc();
								android.os.Process
										.killProcess(android.os.Process.myPid());
							}
						});

				alert.setCancelable(true);
				alert.show();
			}
			break;
		case R.id.about:
			createAboutMessage();
			break;

		}
		return true;
	}

	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// TODO Auto-generated method stub
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			createExitMessage();
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}

	public void initStory() {
		try {
			// Tạo task kết nối với server
			new AsyncTask<Void, Void, String>() {
				@Override
				protected void onPreExecute() {
					// Hiển thị thông báo
					showDialog(DIALOG_DOWNLOAD_PROGRESS);
				}

				@Override
				protected String doInBackground(Void... arg0) {
					try {

						Thread theard = new Thread() {
							@Override
							public void run() {
								try {

									int waited = 0;
									while (true && (waited < 10000)) {
										sleep(100);
										if (true) {
											waited += 100;
										}
									}

								} catch (Exception e) {
									// do nothing
								} finally {
									try {
										System.out
												.println("Không kết nối được đến server");
										dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
									} catch (Exception e) {
										// TODO: handle exception
									}
								}
							}
						};
						theard.start();

						CHandler.storyList = XMLParser
								.getStoryList("http://data.ikame.vn/f17/index.php");

					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
						System.out.println("Không kết nối được đến server 2");
						try {
							detailsTracker
									.trackPageView("Connection error - StoryList");
							detailsTracker.dispatch();
						} catch (Exception de) {
							// TODO: handle exception
						}
					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
						System.out.println("Không kết nối được đến server 3");
						try {
							detailsTracker
									.trackPageView("Connection error - StoryList");
							detailsTracker.dispatch();
						} catch (Exception de) {
							// TODO: handle exception
						}
					}
					return "";
				}

				// Hoàn thành truy vấn
				@Override
				protected void onPostExecute(String result) {

					try {
						arrayAdapter = new ListStoryAdapter(StoryList.this,
								R.layout.listview_story, CHandler.storyList);

						list = (ListView) findViewById(R.id.list_story);
						list.setAdapter(arrayAdapter);

						list.setOnItemClickListener(new OnItemClickListener() {

							@Override
							public void onItemClick(AdapterView<?> parent,
									View view, int position, long id) {
								// TODO Auto-generated method stub
								CHandler.storyName = CHandler.storyList.get(
										CHandler.storyList.size() - 1
												- position).getName();
								CHandler.storyID = CHandler.storyList.get(
										CHandler.storyList.size() - 1
												- position).getId();

								startActivity(new Intent(StoryList.this,
										ChapList.class));
								StoryList.this.finish();
							}

						});

						if (!CHandler.store.isShowAbout()) {
							createAboutMessage();
							CHandler.store.setShowAbout(true);

							generalTracker
									.trackPageView("FromF17WithLove_installApp");
							generalTracker.dispatch();

							detailsTracker
									.trackPageView("FromF17WithLove_installApp");
							detailsTracker.dispatch();
						}

					} catch (Exception e) {
					}
					try {
						dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
					} catch (Exception e) {
						// TODO: handle exception
					}
				}
			}.execute();
		} catch (Exception e) {
		}
	}

	public void createExitMessage() {
		alert = new AlertDialog.Builder(this);
		alert.setTitle("Thoát ứng dụng");
		alert.setMessage("Bạn có muốn rate app này trên play store?");
		alert.setPositiveButton("Có, đi đến play store",
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int whichButton) {
						Intent intent = new Intent(Intent.ACTION_VIEW);
						intent.setData(Uri
								.parse("market://details?id=vn.ikame.android.truyenf17"));
						startActivity(intent);
					}
				});

		alert.setNegativeButton("Không, tôi muốn thoát luôn",
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int whichButton) {
						StoryList.this.finish();
						System.gc();
						android.os.Process.killProcess(android.os.Process
								.myPid());
					}
				});
		alert.setCancelable(true);
		alert.show();
	}

	@Override
	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case DIALOG_DOWNLOAD_PROGRESS:
			mProgressDialog = new ProgressDialog(this);
			mProgressDialog.setMessage("Loading...");
			mProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
			mProgressDialog.setCancelable(true);
			mProgressDialog.show();
			return mProgressDialog;
		default:
			return null;
		}
	}

	public void initChapList() {
		try {
			// Tạo task kết nối với server
			new AsyncTask<Void, Void, String>() {
				@Override
				protected void onPreExecute() {
					// Hiển thị thông báo
					showDialog(DIALOG_DOWNLOAD_PROGRESS);
				}

				@Override
				protected String doInBackground(Void... arg0) {
					try {

						Thread theard = new Thread() {
							@Override
							public void run() {
								try {

									int waited = 0;
									while (true && (waited < 10000)) {
										sleep(100);
										if (true) {
											waited += 100;
										}
									}

								} catch (Exception e) {
									// do nothing
								} finally {
									try {
										System.out
												.println("Không kết nối được đến server");
										dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
									} catch (Exception e) {
										// TODO: handle exception
									}
								}
							}
						};
						theard.start();

						CHandler.storyName = CHandler.store.getStoryName();
						CHandler.chapID = CHandler.store.getChapID();
						CHandler.storyID = CHandler.store.getStoryID();
						CHandler.chapPos = CHandler.store.getChapPos();
						CHandler.chapList = XMLParser
								.getChapList("http://data.ikame.vn/f17/index.php?cateid="
										+ CHandler.storyID);
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
						System.out.println("Không kết nối được đến server 22");
						try {
							StoryList.detailsTracker
									.trackPageView("Connection error - ChapList");
							StoryList.detailsTracker.dispatch();
						} catch (Exception de) {
							// TODO: handle exception
						}

					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
						System.out.println("Không kết nối được đến server 33");
						try {
							StoryList.detailsTracker
									.trackPageView("Connection error - ChapList");
							StoryList.detailsTracker.dispatch();
						} catch (Exception de) {
							// TODO: handle exception
						}
					}
					return "";
				}

				// Hoàn thành truy vấn
				@Override
				protected void onPostExecute(String result) {
					try {
						dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
					} catch (Exception e) {
						// TODO: handle exception
					}
					CHandler.chapID = CHandler.store.getChapID();
					CHandler.storyID = CHandler.store.getStoryID();
					CHandler.chapPos = CHandler.store.getChapPos();

					try{
						CHandler.chapName = CHandler.chapList.get(CHandler.chapPos)
								.getChapName();
						CHandler.chapID = CHandler.chapList.get(CHandler.chapPos)
								.getId();
						StoryList.this.finish();
						startActivity(new Intent(StoryList.this, Content.class));
					}catch (Exception e) {
						// TODO: handle exception
					}

				}
			}.execute();
		} catch (Exception e) {
		}
	}

}
